#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
验证动态扩展功能的脚本
"""

import os
import sys
from openpyxl import load_workbook

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

def verify_dynamic_expansion():
    """验证动态扩展功能"""
    print("=== 验证动态扩展功能 ===")

    # 检查生成的文件
    output_file = "data/output/test2_dynamic_expansion/test2_resource_plan.xlsx"

    if not os.path.exists(output_file):
        print(f"错误: 文件不存在 {output_file}")
        return False

    try:
        # 加载工作簿
        wb = load_workbook(output_file, data_only=False)

        # 检查リソース計画工作表
        if "リソース計画" in wb.sheetnames:
            ws = wb["リソース計画"]
            print("成功: 找到リソース計画工作表")

            # 验证个人分配区域的扩展
            print("\n--- 个人分配区域验证 ---")

            # 统计担当者数量
            person_count = 0
            for row in range(11, 25):  # 扩展检查范围
                cell_c = ws.cell(row=row, column=3)  # C列：担当者
                if cell_c.value and "担当者" in str(cell_c.value):
                    person_count += 1
                    print(f"第{row}行: {cell_c.value}")
                elif cell_c.value is None:
                    break

            print(f"\n发现担当者数量: {person_count}人")

            # 验证合计行位置
            print("\n--- 合计行位置验证 ---")
            expected_total_row = 11 + person_count

            for row in range(20, 25):
                cell_b = ws.cell(row=row, column=2)  # B列
                if cell_b.value and "合計" in str(cell_b.value):
                    print(f"合计行位置: 第{row}行")
                    print(f"期望位置: 第{expected_total_row}行")

                    if row == expected_total_row:
                        print("成功: 合计行位置正确")
                    else:
                        print("警告: 合计行位置可能不正确")

                    # 验证合计公式
                    cell_e = ws.cell(row=row, column=5)  # E列合计公式
                    if cell_e.value and "SUM(" in str(cell_e.value):
                        print(f"合计公式: {cell_e.value}")

                        # 检查公式范围是否正确更新
                        expected_range = f"E11:E{10 + person_count}"
                        if expected_range in str(cell_e.value):
                            print("成功: 合计公式范围已正确更新")
                        else:
                            print(f"警告: 合计公式范围可能不正确，期望包含 {expected_range}")
                    break

            # 验证角色分布
            print("\n--- 角色分布验证 ---")
            pm_count = 0
            se_count = 0

            for row in range(11, 11 + person_count):
                cell_d = ws.cell(row=row, column=4)  # D列：役割
                if cell_d.value == "PM":
                    pm_count += 1
                elif cell_d.value == "SE":
                    se_count += 1

            print(f"PM担当者: {pm_count}人")
            print(f"SE担当者: {se_count}人")
            print(f"总计: {pm_count + se_count}人")

            # 验证与预期是否一致
            expected_pm = 5  # 2+2+1
            expected_se = 6  # 2+3+1
            expected_total = 11

            if pm_count == expected_pm and se_count == expected_se:
                print("成功: 角色分布符合预期")
                return True
            else:
                print(f"错误: 角色分布不符合预期 (PM期望{expected_pm}实际{pm_count}, SE期望{expected_se}实际{se_count})")
                return False
        else:
            print("错误: 未找到リソース計画工作表")
            return False

    except Exception as e:
        print(f"错误: 验证过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        if 'wb' in locals():
            wb.close()

def create_verification_report():
    """创建验证报告"""
    print("\n=== 创建验证报告 ===")

    output_file = "data/output/test2_dynamic_expansion/test2_resource_plan.xlsx"
    report_file = "data/output/test2_dynamic_expansion/test2_expansion_verification.txt"

    try:
        wb = load_workbook(output_file, data_only=False)

        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("=== test2动态扩展验证报告 ===\n\n")

            if "リソース計画" in wb.sheetnames:
                ws = wb["リソース計画"]

                f.write("--- リソース計画动态扩展验证 ---\n")

                # 个人分配数据检查
                person_count = 0
                f.write("个人分配数据检查:\n")
                for row in range(11, 25):
                    cell_c = ws.cell(row=row, column=3)  # C列：担当者
                    cell_d = ws.cell(row=row, column=4)  # D列：役割

                    if cell_c.value and "担当者" in str(cell_c.value):
                        person_count += 1
                        # 检查时间分配
                        time_assignments = []
                        for col in range(5, 8):  # E-G列（2-4月）
                            cell_val = ws.cell(row=row, column=col).value
                            if cell_val and cell_val != 0:
                                time_assignments.append(f"{col-4}月={cell_val}")

                        f.write(f"  第{row}行: {cell_c.value}, 角色={cell_d.value}, {', '.join(time_assignments)}\n")
                    elif cell_c.value is None:
                        break

                f.write(f"\n总共生成了{person_count}个担当者\n")

                # 合计行检查
                f.write(f"\n--- 合计行验证 ---\n")
                for row in range(20, 25):
                    cell_b = ws.cell(row=row, column=2)
                    if cell_b.value and "合計" in str(cell_b.value):
                        f.write(f"合计行位置: 第{row}行\n")
                        f.write(f"期望位置: 第{11 + person_count}行\n")

                        # 检查合计公式
                        cell_e = ws.cell(row=row, column=5)
                        if cell_e.value:
                            f.write(f"合计公式: {cell_e.value}\n")
                        break

                # 角色分布统计
                pm_count = se_count = 0
                for row in range(11, 11 + person_count):
                    cell_d = ws.cell(row=row, column=4)
                    if cell_d.value == "PM":
                        pm_count += 1
                    elif cell_d.value == "SE":
                        se_count += 1

                f.write(f"\n角色分布:\n")
                f.write(f"  PM: {pm_count}人\n")
                f.write(f"  SE: {se_count}人\n")

                # 验证结果
                f.write(f"\n--- 期望vs实际对比 ---\n")
                f.write(f"期望总担当者数: 11人\n")
                f.write(f"实际总担当者数: {person_count}人\n")

                if person_count == 11 and pm_count == 5 and se_count == 6:
                    f.write(f"✓ 动态扩展成功，担当者数量和角色分布均正确\n")
                else:
                    f.write(f"× 动态扩展存在问题\n")

        print(f"验证报告已生成: {report_file}")

    except Exception as e:
        print(f"错误: 生成报告失败: {e}")
    finally:
        if 'wb' in locals():
            wb.close()

if __name__ == "__main__":
    success = verify_dynamic_expansion()
    create_verification_report()

    if success:
        print("\n=== 动态扩展功能验证成功 ===")
    else:
        print("\n=== 动态扩展功能验证失败 ===")